import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/ReflectRecordModel.dart';
import 'package:qgchat/http/models/intodetailsModel.dart';
import 'package:qgchat/states/states_model/index.dart';

class InviteFriendsBloc implements BlocBase {
  InviteFriendsBloc(String token) {
    _token = token;
    reflectRecord(token);
    intodetails(token);
  }

  String _token;

  /// 邀请码控制器
  TextEditingController codeC = TextEditingController();

  /// 用户支付宝账号
  TextEditingController alipayAccount = TextEditingController();

  /// 用户支付宝姓名
  TextEditingController alipayMember = TextEditingController();

  // ##########  DEFAULT  ##############

  /// 用户总金额默认值
  final ReflectRecordModel tomalsum = ReflectRecordModel.fromJson({'tomalsum': 0});

  // ##########  STREAMS  ##############

  /// 邀请明细stream
  StreamController _intodetails = StreamController<List<IntodetailsModel>>.broadcast();
  Sink get _intodetailsSink => _intodetails.sink;
  Stream get intodetailsStream => _intodetails.stream;

  /// 用户总金额stream
  StreamController _reflectRecord = StreamController.broadcast();
  Sink get _reflectRecordSink => _reflectRecord.sink;
  Stream get reflectRecordStream => _reflectRecord.stream;

  void dispose() {
    _intodetails.close();
    _reflectRecord.close();
  }

  // ##########  HANDLING  ##############

  /// 填写邀请码
  void sharehref(context) async {
    if (codeC.text.length != 6) {
      showToast("邀请码必须6位");
      return;
    }
    Map result = await UserApis.sharehref(_token, codeC.text);
    if (result['status'] == 1) {
      showToast("填写成功");
      UserState user = state(context, 'user');
      user.userInfo();
    }
  }

  /// 邀请明细
  void intodetails(String token) async {
    List<IntodetailsModel> result = await UserApis.intodetails(token);
    _intodetailsSink.add(result);
  }

  /// 用户总金额
  void reflectRecord(String token) async {
    ReflectRecordModel result = await UserApis.reflectRecord(token);
    if (result.tomalsum == null) {
      result.tomalsum = 0;
    }
    _reflectRecordSink.add(result);
  }

  /// 填写支付宝账号姓名
  void comfiralipay(id, memberToken, callback) async {
    String alipayUser = alipayAccount.text;
    String alipayName = alipayMember.text;
    Map result = await UserApis.comfiralipay(id, memberToken, alipayUser, alipayName);
    if (result != null && result['status'] == 1) {
      showToast(result['msg']);
      _reflectRecordSink.add(result);
      callback();
    }
  }
}
